import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { ICarsHome,ICarBrand} from '@/utils/interface';
import { GetCarBrand,GetBaoJia} from '@/services/index';

// 模板数据
export interface CarsModelState {
    carsList: ICarsHome[],//获取全部汽车品牌接口
    carBrandList:ICarBrand[],//汽车车系数据
    name:string,
    obj:any,
}

// 模板类型
export interface CarsModelType {
    namespace: 'cars';
    state: CarsModelState;
    effects: {
      GetCarBrand: Effect;
      GetBaoJia:Effect;
    };
    reducers: {
      save: Reducer<CarsModelState>;
    };
}
const CarsModel: CarsModelType = {
    namespace: 'cars',
    state: {
      carsList: [],
      carBrandList:[],
      name:'',
      obj:{},
    },
    // 异步操作，理解为vuex中的action, async/await理解为generator函数的语法糖
    effects:{
      //获取全部汽车品牌接口
      *GetCarBrand({ payload }, { call, put }) {
        let result = yield call(GetCarBrand);
        const list=['A','B','C','D','F','G','H','J','K','L','M','N','O','P','Q','R','S','T','W','X','Y','Z']
        const obj:any={}
        list.forEach((item,index) =>{
          obj[item]=[];
          // 把字符串转换为大写
          (result.data as ICarsHome[]).forEach(i =>{
            if(i.Spelling[0].toLocaleUpperCase() === item){
              obj[item].push(i)
            }
          })
        });
        yield put({
          type: 'save',
          payload: { carsList: result.data,obj }
        })
      },
      *GetBaoJia({payload},{call,put}){
          let result = yield call(GetBaoJia,payload)
          yield put({
            type:'save',
            payload:{carBrandList:result.data}
          })
      }
      // 添加考试
    // *getExam({payload},{call,put}){
    //     let result = yield call(getExam, payload)
    //     return result
    //  },
  
    },
    // 同步操作，理解为vuex中的mutation
    reducers: {
      save(state, action) {
        return {
          ...state,
          ...action.payload,
        };
      }
    }
};
export default CarsModel;